package com.cmccsi.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.cmccsi.entity.User;
import com.cmccsi.mapper.UserMapper;
import com.cmccsi.service.UserService;
import com.cmccsi.utils.MybatisUtil;

public class UserServiceImpl implements UserService {
	
	private SqlSessionFactory sessionFactory = MybatisUtil.getInstance();
	
	@Override
	public void save(User user) {
		SqlSession session = sessionFactory.openSession();
		try {
			UserMapper userMapper = session.getMapper(UserMapper.class);
			userMapper.save(user);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	@Override
	public void update(User user) {
		SqlSession session = sessionFactory.openSession();
		try {
			UserMapper userMapper = session.getMapper(UserMapper.class);
			userMapper.update(user);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	@Override
	public User find(int id) {
		User user = null;
		SqlSession session = sessionFactory.openSession();
		try {
			UserMapper userMapper = session.getMapper(UserMapper.class);
			user = userMapper.find(id);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return user;
	}

	@Override
	public void delete(int id) {
		SqlSession session = sessionFactory.openSession();
		try {
			UserMapper userMapper = session.getMapper(UserMapper.class);
			userMapper.delete(id);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	@Override
	public List<User> findAll() {
		List<User> list = new ArrayList<User>();
		SqlSession session = sessionFactory.openSession();
		try {
			UserMapper userMapper = session.getMapper(UserMapper.class);
			list = userMapper.findAll();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return list;
	}

	@Override
	public Map checkLogin(Map map) {
		Map resultMap = null;
		SqlSession session = sessionFactory.openSession();
		try {
			UserMapper userMapper = session.getMapper(UserMapper.class);
			resultMap = userMapper.checkLogin(map);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return resultMap;
		
	}

}
